package com.szgd.service.personnel;

import com.szgd.bean.Attach;
import com.szgd.bean.SysDict;
import com.szgd.dao.ecdata.personnel.HealthMapper;
import com.szgd.paging.Order;
import com.szgd.paging.PageBounds;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.service.sys.SysDictService;
import com.szgd.util.Constant;
import com.szgd.util.StringUtil;
import com.szgd.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class HealthService extends SimulateBaseService {
    @Autowired
    HealthMapper healthMapper;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    PersonnelInfoService personnelInfoService;

    public List<Map<String, Object>> getHealthListNoPage(Map<String, Object> params) {
        List<Map<String, Object>>  healthInfoList = healthMapper.getHealthList(params);
        return healthInfoList;
    }

    public List<Map<String, Object>> getHealthList(Map<String, Object> params) {
        String sortColumn = "PHYSICALDATE"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        return getSqlSession().selectList("com.szgd.dao.ecdata.personnel.HealthMapper.getHealthList", params,pageBounds);
    }

    public Map<String,Object> getHealthDetailInfo(Long id){
        return healthMapper.getHealthDetailInfo(id);
    }

    public void saveHealthInfo(Map<String, Object> params){
        healthMapper.saveHealthInfo(params);
    }

    public int deleteHealth(Map<String, Object> params){
        return healthMapper.deleteHealth(params);
    }

    public List<Map<String,Object>> getAllPerson(){
        return healthMapper.getAllPerson();
    }

    public Map<String,Object> getPersonnelInfo(Map<String, Object> params){
        Map<String,Object> res = healthMapper.getPersonnelInfo(params);;
        String sex = res.get("SEX")==null?"":res.get("SEX").toString();
        if(sex != null && sex.length() > 0){
            if(sex.equalsIgnoreCase("0")){
                res.put("SEX","女");
            }else if(sex.equalsIgnoreCase("1")){
                res.put("SEX","男");
            }
        }
        return res;
    }

    public void insertHealthInfo(Map<String, Object> params) {
        healthMapper.insertHealthInfo(params);
    }

    public void insertHealthAttach(Attach attach) {
        healthMapper.insertHealthAttach(attach);
    }

    public Map<String,Object> getHealthAttach(Long id){
        return healthMapper.getHealthAttach(id);
    }

    public Map<String, String> getFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("name","姓名");
        fieldMapping.put("physicalDate","体检日期");
        fieldMapping.put("hospital","体检医院");
        fieldMapping.put("physicalResult","体检结果");
        fieldMapping.put("remark","备注");

        return fieldMapping;
    }

    public Map<String, Object> batchImportHealth(List<Map<String, Object>> healthList,String userId,String batchNo) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> successList = new ArrayList<>();   //记录导入成功的数据
        List<Map<String, Object>> updateList = new ArrayList<>();   //记录更新的数据
        List<Map<String, Object>> failedList = new ArrayList<>();   //记录导入失败的数据
        List<Map<String, Object>> ignoreList = new ArrayList<>();   //记录忽略的数据


        for (Map<String, Object> healthMap : healthList) {
            HashMap<String, Object> sourceDataMap = new HashMap<String, Object>(healthMap);
            try {
//                if(healthMap.get("contractNumber") != null && StringUtil.isNotBlank(String.valueOf(healthMap.get("contractNumber")))) {
//                }else{
//                    sourceDataMap.put("ERROR_MSG","合同编号为必填项");
//                    failedList.add(sourceDataMap);
//                    continue;
//                }

                if(healthMap.get("name") != null && StringUtil.isNotBlank(String.valueOf(healthMap.get("name")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","姓名为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                //验证是否有该人员
                if(healthMap.get("name") != null && StringUtil.isNotBlank(String.valueOf(healthMap.get("name")))) {
                    String name = healthMap.get("name").toString();
//                    String contractNumber = healthMap.get("contractNumber").toString();
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("name",name);
//                    temp.put("contractNumber",contractNumber);
                    Map<String, Object> person = personnelInfoService.getPersonnelInfo(temp);
                    if(person==null || person.size()==0){
                        sourceDataMap.put("ERROR_MSG","请校验人员姓名");
                        failedList.add(sourceDataMap);
                        continue;
                    }else{
                        String personnelId = person.get("id").toString();
                        healthMap.put("personnelId",personnelId);
                    }
                }

                if(healthMap.get("physicalDate") != null && StringUtil.isNotBlank(String.valueOf(healthMap.get("physicalDate")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","体检日期为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }

                if(healthMap.get("hospital") != null && StringUtil.isNotBlank(String.valueOf(healthMap.get("hospital")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","体检医院为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }

                //验证日期是否准确
                if(healthMap.get("physicalDate") != null && StringUtil.isNotBlank(String.valueOf(healthMap.get("physicalDate")))) {
                    String physicalDate = healthMap.get("physicalDate").toString();
                    boolean res = TimeUtil.isValidDate(physicalDate);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","体检日期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                if(healthMap.get("physicalResult") != null && StringUtil.isNotBlank(String.valueOf(healthMap.get("physicalResult")))) {
                    healthMap.put("PARENT_CODE", "PHYSICAL_RESULT");
                    healthMap.put("DICT_VALUE", healthMap.get("physicalResult"));
                    List<SysDict> resList = sysDictService.getAllSysDict(healthMap);
                    if (resList != null && resList.size() > 0) {
                        SysDict dict = resList.get(0);
                        healthMap.put("physicalResult", dict.getCode());
                    } else {
                        sourceDataMap.put("ERROR_MSG","体检结果填写不正确(参考数据字典)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("personnelId",healthMap.get("personnelId"));
                paramMap.put("physicalDate",healthMap.get("physicalDate"));
                List<Map<String, Object>> healthInfoList =  this.getHealthListNoPage(paramMap);
                if (healthInfoList != null && healthInfoList.size() > 0)
                {
                    healthMap.put("id",healthInfoList.get(0).get("id"));
                    healthMap.put("uploader",userId);
                    healthMapper.saveHealthInfo(healthMap);
                    updateList.add(healthMap);
                }
                else {
                    healthMap.put("creator",userId);
                    healthMapper.insertHealthInfo(healthMap);
                    successList.add(healthMap);
                }

            }catch (Exception e){
                String errorMsg = e.getMessage();
                if(errorMsg.indexOf("###",10) != -1){
                    errorMsg = errorMsg.substring(0,errorMsg.indexOf("###",10));
                }
                sourceDataMap.put("ERROR_MSG",errorMsg);
                //记录导入失败记录
                failedList.add(sourceDataMap);
            }
        }

        //组装本次导入的结果
        resultMap.put(Constant.IMPORT_HE_SUCCESS,successList);
        resultMap.put(Constant.IMPORT_HE_IGNORE,ignoreList);
        resultMap.put(Constant.IMPORT_HE_FAILED,failedList);
        resultMap.put(Constant.IMPORT_HE_UPDATED,updateList);
        return resultMap;
    }
}
